package com.juc.concurrency.jucExample.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号量
 * 设置了3个许可，且每1个线程每次都是获取3个许可，因此同一时间只能有1个线程执行
 * 注意 此示例要观察控制台久一些 看输出
 * acquire(int permits)改成0,1,2,4看看效果
 */
@Slf4j
public class SemaphoreExample5 {

    private final static int threadCount = 30;

    public static void main(String[] args) throws Exception {

        ExecutorService exec = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(3);


        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    semaphore.acquire(3); // 【线程维度】获取多个许可
                    test(threadNum);
                    semaphore.release(3); // 【线程维度】释放多个许可
                } catch (Exception e) {
                    log.error("exception", e);
                }
            });
        }
        exec.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        log.info("{}", threadNum);
        Thread.sleep(2000);
    }
}
